package com.netintech.intelligenceInterface.common.interceptor;

import com.netintech.intelligenceInterface.common.customException.InterfaceCallException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import static com.netintech.intelligenceInterface.common.StaticBean.*;
import static com.netintech.intelligenceInterface.common.Type.FREQUENCY_LIMIT;

/**
 * @author lining
 * @date 2021/5/6 14:31
 * ip地址拦截器  如果一个Ip一秒钟内有10次访问，则拒绝此次请求
 */
@Component
public class IpInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String ipAddress = request.getRemoteHost();
        String blackIp = BLACK_IP_PREFIX + ipAddress;
        if (redisTemplate.hasKey(blackIp)) {
            throw new InterfaceCallException(FREQUENCY_LIMIT, "调用过于频繁,请稍候再试！");
        }
        String now = LOCAL_DATE_FORMAT.get().format(new Date());
        String second = now.substring(now.length() - 2);
        String key = IP_PREFIX + second + "_" + ipAddress;
        if (redisTemplate.hasKey(key)) {
            int count = (int) redisTemplate.boundValueOps(key).get();
            if (count >= MAX_COUNT_EVERY_SECOND) {
                redisTemplate.boundValueOps(blackIp).set(1, 10, TimeUnit.MINUTES);
                throw new InterfaceCallException(FREQUENCY_LIMIT, "调用过于频繁,请稍候再试！");
            } else {
                redisTemplate.boundValueOps(key).set(++count, 1, TimeUnit.SECONDS);
            }
        } else {
            redisTemplate.boundValueOps(key).set(1, 1, TimeUnit.SECONDS);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }
}
